package com.timoon.component.panel.tree.ztree.checkboxtree;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.wicket.markup.html.form.Button;

/**
 *<p></p>
 *<p></p>
 *<p>Copyright:Copyright(c)2013.4.1</p>
 *<p>Company:timoon</p>
 *@author 付乐天
 *@version 1.0 */
public class CheckboxParameter implements java.io.Serializable{

	private List<Object> datas;
	private String idProperty;
	private String pIdProperty;
	private String textProperty;
	private List<String> checkedIds;
	
	/**
	 * 
	 * @param datas 数据源
	 * @param idProperty
	 * @param pIdProperty
	 * @param textProperty
	 */
	public CheckboxParameter(List<Object> datas,String idProperty,String pIdProperty,String textProperty) {
		// TODO Auto-generated constructor stub
		this.datas=datas;
		this.idProperty=idProperty;
		this.pIdProperty=pIdProperty;
		this.textProperty=textProperty;
	}
	/**
	 * 
	 * @param datas
	 * @param idProperty
	 * @param pIdProperty
	 * @param textProperty
	 * @param checkedIds 已选中的id集合
	 */
	public CheckboxParameter(List<Object> datas,String idProperty,String pIdProperty,String textProperty,List<String> checkedIds) {
		// TODO Auto-generated constructor stub
		this.datas=datas;
		this.idProperty=idProperty;
		this.pIdProperty=pIdProperty;
		this.textProperty=textProperty;
		this.checkedIds=checkedIds;
	}
	public String getJSON(){
		StringBuffer json=new StringBuffer("[");
		if(datas!=null&&datas.size()>0){
			for(Object obj:datas){
				try {
					String id=BeanUtils.getProperty(obj, idProperty);
					String pId=BeanUtils.getProperty(obj, pIdProperty);
					String name=BeanUtils.getProperty(obj, textProperty);
					
					boolean checked=false;
					if(this.checkedIds!=null&&this.checkedIds.size()>0){
						checked=this.checkedIds.contains(id);
					}
					json.append(this.getRecord(id, pId, name, checked, false)+",");
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			json.deleteCharAt(json.length()-1);
		}
		json.append("]");
		
		return json.toString();
	}
	private String getRecord(String id,String pId,String text,boolean checked,boolean open){
		String record="{\"id\":"+id+",\"pId\":"+pId+",\"name\":\""+text+"\",\"checked\":"+checked+",\"open\":"+open+"}";
		return record;
	}
	

}
